package com.black.app.service.impl.my;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.black.app.domain.my.AppMyHabitDetail;
import com.black.app.domain.req.my.mydata.AppMyDataHabitDetailAddReq;
import com.black.app.service.my.AppMyHabitDetailService;
import com.black.app.mapper.my.AppMyHabitDetailMapper;
import com.black.common.exception.ServiceException;
import com.black.common.utils.MessageUtils;
import com.black.common.utils.SecurityUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
* @author 18494
* @description 针对表【app_my_habit_detail(习惯详情表)】的数据库操作Service实现
* @createDate 2024-10-23 20:49:29
*/
@Service
public class AppMyHabitDetailServiceImpl extends ServiceImpl<AppMyHabitDetailMapper, AppMyHabitDetail>
    implements AppMyHabitDetailService{

    @Override
    public boolean addHabit(AppMyDataHabitDetailAddReq req) {

        req.setUserId(SecurityUtils.getAppLoginUser().getUserId());

        // 判断日期是否存在
        if (this.baseMapper.exists(new LambdaQueryWrapper<AppMyHabitDetail>().eq(AppMyHabitDetail::getDate, req.getDate()))) {
            throw new ServiceException(MessageUtils.message("app.my.detail.date.exists"));
        }

        if (req.getFinish()> 4) {
            throw new ServiceException(MessageUtils.message("app.my.detail.finish.error"));
        }

        req.setFinished(req.getFinish() * 25);

        AppMyHabitDetail newEntity = new AppMyHabitDetail();

        BeanUtils.copyProperties(req, newEntity);

        boolean save = this.save(newEntity);

        return save;
    }

    @Override
    public PageInfo<AppMyHabitDetail> getHabit(AppMyDataHabitDetailAddReq req) {
        req.setUserId(SecurityUtils.getAppLoginUser().getUserId());
        return PageHelper.startPage(req.getPageNum(), req.getPageSize()).doSelectPageInfo(() -> {
            this.baseMapper.getHabit(req);
        });
    }

    @Override
    public boolean deleteById() {
        // 获取当前登录用户的用户id
        Long userId = SecurityUtils.getAppLoginUser().getUserId();
        // 删除AppMyHabitDetail表中的id最大的数据
        int id = this.baseMapper.selectOne(new LambdaQueryWrapper<AppMyHabitDetail>()
                    .eq(AppMyHabitDetail::getUserId, userId)
                    .orderByDesc(AppMyHabitDetail::getId).last("limit 1")).getId();
        // 删除
        boolean result = this.removeById(id);
        return result;
    }
}




